package com.spzx.order.receiver;


import com.rabbitmq.client.Channel;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.order.configure.DeadLetterMqConfig;
import com.spzx.order.configure.DelayedMqConfig;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class TestReceiver {


    @Autowired
    private RedisTemplate redisTemplate;

    @RabbitListener(queues = "spzx.test")
    public void receive(Channel channel, String msg, Message message) {
        byte[] body = message.getBody();
        String s = new String(body);
        log.info("接收消息：{}", s);
        log.info("接收消息：{}", msg);
    }

    @RabbitListener(queues = MqConst.QUEUE_CONFIRM)
    public void confirm(Channel channel, Object msg, Message message) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            log.info("接收确认消息：{}", msg);
            byte[] body = message.getBody();
            String s = new String(body);
            log.info("接收确认消息：{}", s);
        } catch (Exception e) {
            channel.basicNack(deliveryTag, false, true);
        }
        channel.basicAck(deliveryTag, false);
    }

//    @RabbitListener(queues = DelayedMqConfig.queue_delay_1)
//    public void delay(Channel channel, Object msg, Message  message) throws IOException {
//        long deliveryTag = message.getMessageProperties().getDeliveryTag();
//        String key = "mq:" + msg;
//        Boolean isLock = redisTemplate.opsForValue().setIfAbsent(key, "", 200, TimeUnit.SECONDS);
//        if(Boolean.FALSE.equals(isLock)){
//            channel.basicAck(deliveryTag,  false);
//            return;
//        }
//        try{
//            log.info("接收延迟消息：{}", msg);
//            byte[] body = message.getBody();
//            String s = new String(body);
//            log.info("接收延迟消息：{}", s);
//            channel.basicAck(deliveryTag,  false);
//        }catch (Exception e){
//            channel.basicNack(deliveryTag,  false, true);
//        }
//    }


    @SneakyThrows
    @RabbitListener(queues = DeadLetterMqConfig.queue_dead_2)
    public void dead(Channel channel, String msg, Message message) {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            log.info("接收死信队列消息：{}", msg);
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            channel.basicNack(deliveryTag, false, true);
        }
    }

}
